<?php

namespace App\Console\Commands;

use App\Services\WorkerService;
use Exception;
use GatewayWorker\Lib\Gateway;
use Illuminate\Console\Command;

class RunWorkerman extends Command
{

    protected $signature = 'runWorkerman {type}';
    protected $description = 'run worker data';
    private $workerService;

    public function __construct(WorkerService $workerService)
    {
        parent::__construct();
        Gateway::$registerAddress = env('WS_Intranet_ip') . ':9501';
        $this->workerService = $workerService;
    }

    /**
     * Execute the console command.
     * @return bool
     */
    public function handle()
    {
        //获取全局所有在线uid数量
        if (Gateway::getAllUidCount() > 0) {
            $type = $this->argument('type');
            //获取某个分组所有在线client_id_id列表
            if (Gateway::getClientIdCountByGroup($type) > 0) {
                $uid_list = Gateway::getUidListByGroup($type);
                if (!empty($uid_list)) {
                    foreach ($uid_list as $token) {
                        try {
                            if (Gateway::isUidOnline($token)) {
                                $this->resultToClient($type, $token);
                            }
                        } catch (Exception $e) {
                            echo $e->getMessage(), $e->getFile(), $e->getLine(), PHP_EOL;
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 发送结果到客户端
     * @param $type
     * @param $token
     * @return bool
     */
    private function resultToClient($type, $token): bool
    {
        $clientIdList = Gateway::getClientSessionsByGroup($type);
        $currentUserClientIds = Gateway::getClientIdByUid($token);
        if ($clientIdList && $currentUserClientIds) {
            foreach ($clientIdList as $clientId => $sessionCondition) {
                if (!in_array($clientId, $currentUserClientIds)) continue;
                switch ($type) {
                    case 'download':
                        $result = $this->workerService->Download($token, $sessionCondition);
                        break;
                    default:
                        $result = [];
                        break;
                }
                $response = [
                    'client_id' => $clientId,
                    'mode' => $type,
                    'res' => $result
                ];
                Gateway::sendToClient($clientId, json_encode($response));
            }
        }
        return true;
    }
}
